<template>
  <div class="page-container">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="back-btn" @click="goBack">
        <Left />
      </div>
      <h1 class="title">{{ isEdit ? '编辑地址' : '新增地址' }}</h1>
      <div class="save-btn" @click="saveAddress">保存</div>
    </div>

    <!-- 地址表单 -->
    <div class="address-form">
      <div class="form-group">
        <label class="form-label">收货人</label>
        <input 
          v-model="addressForm.name" 
          type="text" 
          placeholder="请输入收货人姓名"
          class="form-input"
        />
      </div>

      <div class="form-group">
        <label class="form-label">手机号码</label>
        <input 
          v-model="addressForm.phone" 
          type="tel" 
          placeholder="请输入手机号码"
          class="form-input"
          maxlength="11"
        />
      </div>

      <div class="form-group">
        <label class="form-label">所在地区</label>
        <div class="region-selector" @click="showRegionSelector">
          <span class="region-text" v-if="addressForm.province && addressForm.city && addressForm.district">
            {{ addressForm.province }} {{ addressForm.city }} {{ addressForm.district }}
          </span>
          <span class="region-placeholder" v-else>请选择所在地区</span>
          <Right class="arrow" />
        </div>
      </div>

      <div class="form-group">
        <label class="form-label">详细地址</label>
        <textarea 
          v-model="addressForm.address" 
          placeholder="请输入详细地址，如街道、门牌号等"
          class="form-textarea"
          rows="3"
        ></textarea>
      </div>

      <div class="form-group">
        <label class="form-label">地址标签</label>
        <div class="tag-selector">
          <span 
            v-for="tag in addressTags" 
            :key="tag"
            class="tag-item"
            :class="{ active: addressForm.tag === tag }"
            @click="addressForm.tag = tag"
          >
            {{ tag }}
          </span>
          <span 
            class="tag-item custom"
            :class="{ active: isCustomTag }"
            @click="showCustomTagInput = true"
          >
            {{ addressForm.tag && !addressTags.includes(addressForm.tag) ? addressForm.tag : '自定义' }}
          </span>
        </div>
        <input 
          v-if="showCustomTagInput"
          v-model="addressForm.tag"
          type="text"
          placeholder="请输入标签名称"
          class="custom-tag-input"
          @blur="handleCustomTagBlur"
        />
      </div>

      <div class="form-group">
        <label class="form-label">设为默认地址</label>
        <nut-switch v-model="addressForm.isDefault" />
      </div>
    </div>

    <!-- 删除按钮 -->
    <div class="delete-section" v-if="isEdit">
      <nut-button 
        type="danger" 
        size="large"
        @click="showDeleteConfirm = true"
        class="delete-btn"
      >
        删除地址
      </nut-button>
    </div>

    <!-- 地区选择弹窗 -->
    <nut-popup v-model:visible="showRegion" position="bottom" :style="{ height: '60%' }">
      <div class="region-popup">
        <div class="popup-header">
          <h3>选择地区</h3>
          <span class="close-btn" @click="showRegion = false">×</span>
        </div>
        <div class="region-tabs">
          <div 
            class="tab-item" 
            :class="{ active: activeRegionTab === 'province' }"
            @click="activeRegionTab = 'province'"
          >
            {{ addressForm.province || '省份' }}
          </div>
          <div 
            class="tab-item" 
            :class="{ 
              active: activeRegionTab === 'city',
              disabled: !addressForm.province 
            }"
            @click="activeRegionTab = 'city'"
          >
            {{ addressForm.city || '城市' }}
          </div>
          <div 
            class="tab-item" 
            :class="{ 
              active: activeRegionTab === 'district',
              disabled: !addressForm.city 
            }"
            @click="activeRegionTab = 'district'"
          >
            {{ addressForm.district || '区县' }}
          </div>
        </div>
        <div class="region-list">
          <div 
            v-for="item in currentRegionList" 
            :key="item"
            class="region-option"
            @click="selectRegion(item)"
          >
            {{ item }}
          </div>
        </div>
      </div>
    </nut-popup>

    <!-- 删除确认弹窗 -->
    <nut-popup v-model:visible="showDeleteConfirm" position="center" :style="{ width: '80%' }">
      <div class="delete-confirm">
        <h3>确认删除</h3>
        <p>确定要删除这个地址吗？删除后无法恢复。</p>
        <div class="confirm-actions">
          <nut-button @click="showDeleteConfirm = false">取消</nut-button>
          <nut-button type="danger" @click="confirmDelete">确认删除</nut-button>
        </div>
      </div>
    </nut-popup>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAddressStore } from '@/stores/address'
import { Left, Right } from '@nutui/icons-vue'

const route = useRoute()
const router = useRouter()
const addressStore = useAddressStore()

// 是否为编辑模式
const isEdit = computed(() => route.params.id !== 'new')

// 地址表单数据
const addressForm = reactive({
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  address: '',
  tag: '家',
  isDefault: false
})

// 地址标签选项
const addressTags = ['家', '公司', '学校']

// 地区选择相关
const showRegion = ref(false)
const activeRegionTab = ref('province')

// 自定义标签输入
const showCustomTagInput = ref(false)

// 删除确认
const showDeleteConfirm = ref(false)

// 地区数据（简化版，实际项目中应该从API获取）
const regionData = {
  '北京市': {
    '北京市': ['东城区', '西城区', '朝阳区', '丰台区', '石景山区', '海淀区', '门头沟区', '房山区', '通州区', '顺义区', '昌平区', '大兴区', '怀柔区', '平谷区', '密云区', '延庆区']
  },
  '上海市': {
    '上海市': ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区', '虹口区', '杨浦区', '闵行区', '宝山区', '嘉定区', '浦东新区', '金山区', '松江区', '青浦区', '奉贤区', '崇明区']
  },
  '广东省': {
    '广州市': ['荔湾区', '越秀区', '海珠区', '天河区', '白云区', '黄埔区', '番禺区', '花都区', '南沙区', '从化区', '增城区'],
    '深圳市': ['罗湖区', '福田区', '南山区', '宝安区', '龙岗区', '盐田区', '龙华区', '坪山区', '光明区']
  }
}

// 当前地区列表
const currentRegionList = computed(() => {
  if (activeRegionTab.value === 'province') {
    return Object.keys(regionData)
  } else if (activeRegionTab.value === 'city') {
    return addressForm.province ? Object.keys(regionData[addressForm.province]) : []
  } else if (activeRegionTab.value === 'district') {
    return addressForm.city && addressForm.province ? regionData[addressForm.province][addressForm.city] : []
  }
  return []
})

// 是否为自定义标签
const isCustomTag = computed(() => {
  return addressForm.tag && !addressTags.includes(addressForm.tag)
})

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 显示地区选择器
const showRegionSelector = () => {
  activeRegionTab.value = 'province'
  showRegion.value = true
}

// 选择地区
const selectRegion = (region) => {
  if (activeRegionTab.value === 'province') {
    addressForm.province = region
    addressForm.city = ''
    addressForm.district = ''
    activeRegionTab.value = 'city'
  } else if (activeRegionTab.value === 'city') {
    addressForm.city = region
    addressForm.district = ''
    activeRegionTab.value = 'district'
  } else if (activeRegionTab.value === 'district') {
    addressForm.district = region
    showRegion.value = false
  }
}

// 处理自定义标签失焦
const handleCustomTagBlur = () => {
  if (!addressForm.tag || addressForm.tag.trim() === '') {
    addressForm.tag = '家'
  }
  showCustomTagInput.value = false
}

// 保存地址
const saveAddress = () => {
  // 验证表单
  const validation = addressStore.validateAddress(addressForm)
  if (!validation.valid) {
    showToast(validation.message)
    return
  }

  try {
    if (isEdit.value) {
      // 编辑模式
      const updated = addressStore.updateAddress(parseInt(route.params.id), addressForm)
      if (updated) {
        showToast('地址更新成功')
        router.go(-1)
      } else {
        showToast('地址更新失败')
      }
    } else {
      // 新增模式
      const newAddress = addressStore.addAddress(addressForm)
      if (newAddress) {
        showToast('地址添加成功')
        router.go(-1)
      } else {
        showToast('地址添加失败')
      }
    }
  } catch (error) {
    console.error('保存地址失败:', error)
    showToast('保存失败，请重试')
  }
}

// 确认删除
const confirmDelete = () => {
  try {
    const success = addressStore.deleteAddress(parseInt(route.params.id))
    if (success) {
      showToast('地址删除成功')
      router.go(-1)
    } else {
      showToast('地址删除失败')
    }
  } catch (error) {
    console.error('删除地址失败:', error)
    showToast('删除失败，请重试')
  }
  showDeleteConfirm.value = false
}

// 显示提示
const showToast = (message) => {
  // 使用NutUI的Toast组件
  try {
    if (typeof window !== 'undefined' && window.nutui && window.nutui.showToast) {
      window.nutui.showToast({
        content: message,
        type: 'success',
        duration: 2000
      })
    } else {
      console.log('Toast提示:', message)
    }
  } catch (error) {
    console.log('Toast提示:', message)
  }
}

// 初始化表单数据
const initFormData = () => {
  if (isEdit.value) {
    const addressId = parseInt(route.params.id)
    const address = addressStore.getAddressById(addressId)
    if (address) {
      Object.assign(addressForm, address)
    } else {
      showToast('地址不存在')
      router.go(-1)
    }
  }
}

onMounted(() => {
  // 加载地址数据
  addressStore.loadFromLocalStorage()
  
  // 初始化表单
  initFormData()
})
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 20px;
}

.header {
  background: white;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #666;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
  flex: 1;
  text-align: center;
}

.save-btn {
  font-size: 16px;
  color: #007bff;
  cursor: pointer;
  padding: 8px 16px;
}

.address-form {
  background: white;
  margin: 12px;
  border-radius: 8px;
  overflow: hidden;
}

.form-group {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.form-group:last-child {
  border-bottom: none;
}

.form-label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  font-size: 14px;
  color: #333;
  background: white;
  box-sizing: border-box;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: #007bff;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.region-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background: white;
  cursor: pointer;
}

.region-text {
  font-size: 14px;
  color: #333;
}

.region-placeholder {
  font-size: 14px;
  color: #999;
}

.arrow {
  color: #ccc;
  font-size: 16px;
}

.tag-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  padding: 8px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;
}

.tag-item:hover {
  border-color: #007bff;
  color: #007bff;
}

.tag-item.active {
  border-color: #007bff;
  background: #007bff;
  color: white;
}

.tag-item.custom {
  border-style: dashed;
}

.custom-tag-input {
  margin-top: 8px;
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  font-size: 14px;
}

.delete-section {
  margin: 12px;
}

.delete-btn {
  width: 100%;
}

/* 地区选择弹窗 */
.region-popup {
  padding: 20px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.popup-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.close-btn {
  font-size: 24px;
  color: #999;
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.region-tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}

.tab-item.active {
  color: #007bff;
  border-bottom-color: #007bff;
}

.tab-item.disabled {
  color: #ccc;
  cursor: not-allowed;
}

.region-list {
  max-height: 300px;
  overflow-y: auto;
}

.region-option {
  padding: 12px;
  font-size: 14px;
  color: #333;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
}

.region-option:hover {
  background: #f5f5f5;
}

/* 删除确认弹窗 */
.delete-confirm {
  padding: 20px;
  text-align: center;
}

.delete-confirm h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
}

.delete-confirm p {
  font-size: 14px;
  color: #666;
  margin: 0 0 20px 0;
  line-height: 1.5;
}

.confirm-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.confirm-actions .nut-button {
  min-width: 80px;
}
</style>
